/*
 * 文 件 名 : HomeActivity.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-8-4
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.ui.diary;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.fire8.dolphin.common.Constants;
import com.fire8.dolphin.db.QuestionDAO;
import com.fire8.dolphin.model.Question;
import com.fire8.dolphin.service.SubmitQuestion;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.utils.DateUtil;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.StringUtil;

/**
 * 主页面
 * 用户输入日志(标题、内容、图片、声音)
 * 显示在能量广场里
 * @author  lixg
 * @version [版本号,2012-8-4]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class QuestionAddActivity extends Activity
{
    //private final int TITLE_LEN=20;
    private EditText txtTitle;
    private EditText txtContext;
    private Button btnEnter;//保存
    private Button btnInputImg;//切换到图片上传页面
    private Button btnInputVoice;//切换到语音输入页面
    private Button btnInputText;//切换到文字输入页面
    private ImageView imgInputVoice;//按住说话的MIC图片
    private ImageView imgInput;//显示图片
    private ImageView imgPlayVoice;//显示回放按钮
    private RelativeLayout layInputVoice;//语音输入布局
    private String strTitle;
    private String strContext;
    DolphinApplication app;
    private String[] items = new String[] { "选择本地图片", "拍照" };
    private String fileName;
    private MediaRecorder mRecorder = null;
    private File mRecAudioPath;
    private File mRecAudioFile;
    private long startTime;//录音开始时间
    private long endTime;//录音结束时间
    private long voiceLong;//录音时长(秒)
    private AnimationDrawable voicePlayAnim;//播放动画
    
    private static final int IMAGE_REQUEST_CODE = 1;
    
    private static final int CAMERA_REQUEST_CODE= 2;
    private static final int RESULT_REQUEST_CODE = 3;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diary_add);
        registerReceiver(this.receiver, new IntentFilter(Constants.VOICE_PLAY_CALLBACK));
        app = (DolphinApplication)getApplication();
        fileName = System.currentTimeMillis()+".jpg";
        txtTitle = (EditText)findViewById(R.id.txt_title);
        txtContext = (EditText)findViewById(R.id.txt_context);
        btnEnter = (Button)findViewById(R.id.btn_enter);
        btnEnter.setOnClickListener(new ButtonClickLienter());
        app = (DolphinApplication)getApplication();
        layInputVoice = (RelativeLayout)findViewById(R.id.lay_input_voice);
        btnInputImg = (Button)findViewById(R.id.btn_input_img);
        btnInputText = (Button)findViewById(R.id.btn_input_txt);
        imgInput = (ImageView)findViewById(R.id.img_input_img);
        imgPlayVoice = (ImageView)findViewById(R.id.img_play_voice);
        
//        imgPlayVoice.setVisibility(View.VISIBLE);
        btnInputVoice = (Button)findViewById(R.id.btn_input_voice);
        imgInputVoice = (ImageView)findViewById(R.id.img_input_voice);
        btnInputImg.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                btnInputImg.setBackgroundResource(R.color.tab_bg_gray_1);
                btnInputVoice.setBackgroundResource(R.color.tab_bg_gray);
                btnInputText.setBackgroundResource(R.color.tab_bg_gray);
                
                layInputVoice.setVisibility(View.GONE);
                imgInput.setVisibility(View.VISIBLE);
                txtContext.setVisibility(View.GONE);
                showDialog();
            }
        });
        btnInputVoice.setOnClickListener(new OnClickListener()
        {
            
            @Override
            public void onClick(View v)
            {
                btnInputVoice.setBackgroundResource(R.color.tab_bg_gray_1);
                btnInputImg.setBackgroundResource(R.color.tab_bg_gray);
                btnInputText.setBackgroundResource(R.color.tab_bg_gray);
                imgInput.setVisibility(View.GONE);
                layInputVoice.setVisibility(View.VISIBLE);
                txtContext.setVisibility(View.GONE);
            }
        });
        btnInputText.setOnClickListener(new OnClickListener()
        {
            
            @Override
            public void onClick(View v)
            {
                btnInputText.setBackgroundResource(R.color.tab_bg_gray_1);
                btnInputVoice.setBackgroundResource(R.color.tab_bg_gray);
                btnInputImg.setBackgroundResource(R.color.tab_bg_gray);
                imgInput.setVisibility(View.GONE);
                layInputVoice.setVisibility(View.GONE);
                txtContext.setVisibility(View.VISIBLE);
            }
        });
        imgInputVoice.setOnLongClickListener(new OnLongClickListener()
        {
            @Override
            public boolean onLongClick(View v)
            {
                startRecording();
                return false;
            }
        });
        imgInputVoice.setOnTouchListener(new OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                if(MotionEvent.ACTION_UP == event.getAction())
                {
                    //停止录音
                    stopRecording();
                    
                    if(mRecAudioFile != null)
                    {
                        LogUtil.d("完成录音： "+mRecAudioFile.getPath());
                        LogUtil.d("文件大小(字节)："+mRecAudioFile.length());
                        LogUtil.d("显示播放按钮");
//                        imgPlayVoice.setImageResource(R.drawable.play_ing0);
                        imgPlayVoice.setVisibility(View.VISIBLE);
                        imgPlayVoice.setBackgroundResource(R.anim.voice_play_w);
                        
                    }
                    
                }
                return false;
            }
        });
        //回放按钮
        imgPlayVoice.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
//                adp = (AnimationDrawable)imgPlayVoice.getBackground();
//                LogUtil.d("动画是否已经启动1？"+adp.isRunning());
//                adp.start();
//                LogUtil.d("启动动画");
//                LogUtil.d("动画是否已经启动2？"+adp.isRunning());
                if(mRecAudioFile != null)
                {
                    voicePlayAnim = (AnimationDrawable)imgPlayVoice.getBackground();
                    if(voicePlayAnim.isRunning())
                    {
                        imgPlayVoice.setImageResource(R.drawable.play3_w);
                        voicePlayAnim.stop();
                        sendMessage(Constants.MEDIA_PAUSE,"");
                    }else
                    {
                        imgPlayVoice.setImageDrawable(null);
                        voicePlayAnim.start();
                        sendMessage(Constants.MEDIA_INIT,mRecAudioFile.getPath());
                    }
                    LogUtil.d("播放录音");
                    //imgPlayVoice.setImageBitmap(null);
                    
                    //启动任务，播放语音、显示动画
//                    VoiceAnimAndPlay task = new VoiceAnimAndPlay();
//                    task.execute(mRecAudioFile.getPath());
                }
            }
        });
    }
    @Override
    protected void onStart()
    {
        super.onStart();
    }
    class ButtonClickLienter implements OnClickListener
    {

        @Override
        public void onClick(View v)
        {
            
            strTitle = txtTitle.getText().toString();
            strContext = txtContext.getText().toString();
            if(StringUtil.isEmpty(strTitle))
            {
                Toast.makeText(QuestionAddActivity.this, "请输入标题", Toast.LENGTH_LONG).show();
                return;
            }
            
            LogUtil.d("strTitle: "+strTitle);
            
            //保存问题到本地
            QuestionDAO dao = new QuestionDAO(QuestionAddActivity.this);
            Question question  = new Question();
            question.setTitle(strTitle);
            question.setContext(strContext);
            question.setUpdateDate(DateUtil.dateToStr(new Date(), "yyyy-MM-dd hh:mm:ss"));
            question.setAnswerNum("0");
            question.setUserId(app.getUserId());
            if(mRecAudioFile != null)
            {
                question.setVoice(mRecAudioFile.getPath());
                question.setVoiceLong(voiceLong);
            }
            question.setPicture((String)imgInput.getTag());
            dao.add(question);
            
            //调用service提交问题到服务器并将返回的问题ID更新到本地
            SubmitQuestion submit = new SubmitQuestion(QuestionAddActivity.this,app);
            submit.execute(question);
            
            //发送消息，更新列表页面
//            Intent intent = new Intent();
//            QuestionAddActivity.this.sendBroadcast(intent);
            QuestionAddActivity.this.finish();//关闭窗口
        }
        
    }
    
    
    /** 弹出对话框获取图片*/
    private void showDialog() 
    {
        new AlertDialog.Builder(this)
        .setTitle("上传图片")
        .setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case 0:
                                Intent intentFromGallery = new Intent();
                                intentFromGallery.setType("image/*"); // 设置文件类型
                                intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
                                startActivityForResult(intentFromGallery,IMAGE_REQUEST_CODE);
                                
                                break;
                        case 1:

                                Intent intentFromCapture = new Intent(
                                                MediaStore.ACTION_IMAGE_CAPTURE);
                                // 判断存储卡是否可以用，可用进行存储
                                if (hasSdcard()) {
                                        intentFromCapture.putExtra(
                                                        MediaStore.EXTRA_OUTPUT,
                                                        Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                                                fileName)));
                                }
                                startActivityForResult(intentFromCapture,CAMERA_REQUEST_CODE);
                                break;
                        }
                }
        })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                }
        }).show();
    }
    
    /** 检查内存卡是否可用 */
    private boolean hasSdcard()
    {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (resultCode == RESULT_CANCELED)
        {
            return;
        }
        switch (requestCode)
        {
            case IMAGE_REQUEST_CODE:
                LogUtil.d(data.getData()+"");
                startPhotoZoom(data.getData());
                //getImageToView(data.getData(),imgInput);
                break;
            
            case CAMERA_REQUEST_CODE:
                if (hasSdcard()) {
                    File tempFile = new File(Environment.getExternalStorageDirectory(),fileName);
                    LogUtil.d(tempFile.getPath());
                    startPhotoZoom(Uri.fromFile(tempFile));
                    //getImageToView(Uri.fromFile(tempFile),imgInput);
                } else {
                        Toast.makeText(this, "未找到存储卡，无法存储照片！",Toast.LENGTH_LONG).show();
                }
                break;
            case RESULT_REQUEST_CODE:
                if (data != null) {
                        getImageToView(data,imgInput);
                }
                break;
        
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 裁剪图片方法实现
     * 
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {

            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            // 设置裁剪
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", 350);
            intent.putExtra("outputY", 350);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, 3);
    }
    /**
     * 保存裁剪之后的图片数据
     * 
     * @param picdata
     */
    private void getImageToView(Intent data,ImageView imgView) {
        Bitmap photo=null;
        Bundle extras = data.getExtras();
        LogUtil.i("保存裁剪之后的图片数据");
        if (extras != null) {
            //LogUtil.d("uri:"+uri.getPath());
            photo = extras.getParcelable("data");
            
//            ContentResolver cr = this.getContentResolver(); 
//            try
//            {
//                photo = BitmapFactory.decodeStream(cr.openInputStream(uri));
//                imgView.setTag(uri2path(uri));
//            }
//            catch (FileNotFoundException e)
//            {
//                LogUtil.e("文件没找到",e);
//            }
            
        }
        if(photo != null)
        {
            
            //imgView.setImageBitmap(photo);
            saveFile(photo);
            imgView.setTag(app.IMG_PATH + photo.hashCode()+".jpg");
            Drawable drawable = new BitmapDrawable(photo);
            imgView.setImageDrawable(drawable);
            LogUtil.d("设置ImageView");
        }
            
    }
    /**从URI获得文件路径**/
    private String uri2path(Uri uri)
    {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = QuestionAddActivity.this.managedQuery(uri,proj,null,null,null);
        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        return actualimagecursor.getString(actual_image_column_index);
    }
    /** 
     * 保存文件 
     * @param bm 
     * @param fileName 
     * @throws IOException 
     */  
    public void saveFile(Bitmap bm){  
        File dirFile = new File(app.IMG_PATH);  
        if(!dirFile.exists()){  
            dirFile.mkdir();  
        }  
        
        try
        {
            File imgFile = new File(app.IMG_PATH + bm.hashCode()+".jpg");  
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imgFile));  
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);  
            bos.flush();
            bos.close();  
            LogUtil.d("保存成功:"+app.IMG_PATH + bm.hashCode()+".jpg");
        }
        catch (IOException e)
        {
            LogUtil.e("写入图像文件失败",e);
        }  
        
    }  
    //==================================================================================
    private void startRecording() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                mRecAudioPath = Environment.getExternalStorageDirectory();
                File fPath = new File(mRecAudioPath.getPath() + File.separator
                                + "RecordList");
                fPath.mkdirs();
                LogUtil.d("创建文件夹"+fPath.getPath());
                mRecAudioFile = fPath;
        } else {
            mRecAudioFile = this.getCacheDir();    
            LogUtil.d("没有插卡或没有读写卡权限，创建文件夹");
        }
        try {
                mRecAudioFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".3gp", mRecAudioFile);
                LogUtil.d("创建文件： "+mRecAudioFile.getPath());
        } catch (IOException e) {
            LogUtil.e("mRec", e);
        }
        
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mRecAudioFile.getPath());
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        try {
            mRecorder.prepare();
            mRecorder.start();
            startTime = System.currentTimeMillis();
            LogUtil.d("开始录音...");
        } catch (IOException e) {
            LogUtil.e( "prepare() failed",e);
        }
        
        
    }
    private void stopRecording() {
        if(mRecorder == null)
            return;
        //if(mRecorder.)
        mRecorder.stop();
        endTime = System.currentTimeMillis();
        voiceLong = (endTime-startTime)/1000;
        mRecorder.release();
        mRecorder = null;
        
        LogUtil.d("停止录音...");
        LogUtil.d(voiceLong+"秒");
    }
    
    /**定义广播接收器**/
    private BroadcastReceiver receiver= new BroadcastReceiver()
    {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            int commend = intent.getIntExtra("command", 0);
            switch (commend)
            {
                case Constants.MEDIA_INIT:
                    //初始化完成,已经开始播放，修改播放状态
                    
                    break;
                case Constants.MEDIA_START:
                    //启动动画
                    if(!voicePlayAnim.isRunning())
                    {
                        imgPlayVoice.setImageDrawable(null);
                        voicePlayAnim.start();
                    }
                    break;
                case Constants.MEDIA_PAUSE:
                    
                    if (voicePlayAnim != null)
                    {
                        imgPlayVoice.setImageResource(R.drawable.play3_w);
                        voicePlayAnim.stop();
                    }
                    break;
                case Constants.MEDIA_STATUS_STOP:
                    //播放完成，修改播放状态
                    if (voicePlayAnim != null)
                    {
                        imgPlayVoice.setImageResource(R.drawable.play3_w);
                        voicePlayAnim.stop();
                    }
                    break;
                default:
                    break;
            }
        }
        
    };
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
    
    /**发送控制指令播或停止语音**/
    private void sendMessage(int command,String param)
    {
        Intent intent = new Intent(Constants.VOICE_PLAY_CONTROL);
        Bundle bundle = new Bundle();
        bundle.putInt("command", command);
        bundle.putString("param", param);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }
    
}
